<?php
/**
  * 栏目控制器
  * date 2013-1-18 
  */
class CategoryAction extends CommonAction {

    private $allCategory=array();
    private $tree=null;
    private $modelArr=null;
    private $typeArr=null;

	  public function _initialize()
	  {
      $this->currentModel = D(MODULE_NAME);
		  parent::_initialize();
      import("@.ORG.Tree");
      $this->allCategory=$this->currentModel->getAllCategory();
      $this->tree=new Tree();
      $this->modelArr=C('MODELTYPE');
      $this->typeArr=C('CATEGORYTYPE');
      $this->assign('typeArray',$this->typeArr);
      $this->assign('modelArray',$this->modelArr);       
	  }

    public function index()
    {  
      $newCategory=$this->_treeData($this->allCategory);
      $treeStr="<tr>
              <td>\$sort_order</td>
              <td>\$id</td>
              <td>\$spacer \$title(模型：\$model 类型：\$is_type)</td>
              <td>\$add_time</td>
              <td>\$status</td>
              <td>
                <a href='__URL__/add/id/\$id' title='添加子栏目' class='mr5'>添加子栏目</a>
                <a href='__URL__/edit/id/\$id' title='编辑' class='mr5'>编辑</a>
                <a href='__URL__/del/id/\$id' title='删除' class='delHandle'>删除</a> 
              </td>
            </tr>";
      
      $this->tree->init($newCategory);
      $treeStr=$this->tree->getTree(0,$treeStr,0);
      $this->assign('treeTrStr',$treeStr);      
    	$this->display();
    }

    /**
      * 构造递归树需要的结构
      * @access private
      * @param array 原始数组
      * @return array 
      */
    private function _treeData($data)
    {
      $treeArr=array();
      foreach($data as $c)
      {
        $c['sort_order']="<input type='text' value='".$c['sort_order']."' name=sort[".$c['id']."]  class='text_input medium_input tc''/>";
        $c['status']=$c['status']==0?'禁止':'开放';
        $c['add_time']=date('Y-m-d H:i:s',$c['add_time']);
        $c['model']=$this->modelArr[$c['model']]['title'];
        $c['is_type']=$this->typeArr[$c['is_type']];
        $treeArr[$c['id']] = $c;
      }
      return $treeArr;
    }

    /**
      * 添加栏目
      * @param pid 父ID
      * 父ID为0或空值，表示添加父栏目
      */
    public function add()
    {
    	if($this->isPost())
    	{
    		$this->_save();
    	}else
    		{
          $parentId=$this->_get($this->pkId);
          if(isset($parentId))
          {
            $parentData=$this->currentModel->field('title')->find($parentId);
            if(empty($parentData))$this->error('参数违法',U(MODULE_NAME.'/index'));
          }
          $this->assign('parentTitle',$parentData['title']);
          $this->assign('parentId',$parentId);
    			$this->display();
    		}
    }

    public function edit()
    {
    	if($this->isPost())
    	{
        $funcName=$this->_post('actionType');
        if(isset($funcName))
        {
          $this->$funcName();
        }else
          {
            $this->_save();
          }
    	}else
    		{
          $id=$this->_get($this->pkId);
          $data=$this->currentModel->find($id);
          if(empty($data))$this->error('参数违法',U(MODULE_NAME.'/index'));
          $this->tree->init($this->allCategory);
          $optionStr=$this->tree->getTree(0,"<option value=\$id \$selected>\$spacer\$title</option>",$data['parent_id']);
          $this->assign('optionStr',$optionStr);         
          $this->assign('data',$data);
    			$this->display('add');
    		}
    }

    /**
      * 删除栏目
      * @access public
      */
    public function del()
    {
      $id=$this->_get($this->pkId);
      if($this->currentModel->where(array('parent_id'=>$id))->count()>0)
      {
        $this->error("此栏目还包含子栏目，请先删除子栏目");
      }
      if(M('Article')->where(array('category_id'=>array('in',$id)))->count()>0)
      {
        $this->error("此栏目还包含内容信息，请先删除内容！");
      }
      if($this->currentModel->delete($id)!=0)
      {
        $this->currentModel->makeCacheFile($this->currentModel->getAllCategory(),MODULE_NAME);
        $this->success('删除成功',U(MODULE_NAME.'/index'));
      }else{$this->error('失败',U(MODULE_NAME.'/index'));}
    }

    /**
      * 插入数据
      * @access private
      */
    private function _save()
    {
    	if($this->currentModel->create()===FALSE)
    	{
    		$this->error($this->currentModel->getError());
    	}
      $id=$this->_post($this->pkId);
      $funcName=$id>0?'save':'add';
      if($funcName=='save')
      {
        $this->_parentCorrect($_POST['parent_id'],$_POST['id']);
      }
      if($this->currentModel->$funcName()!==false)
      {
        $this->currentModel->makeCacheFile($this->currentModel->getAllCategory(),MODULE_NAME);
        $this->success('成功',U(MODULE_NAME.'/index'));
      }else
        {
          $this->error('失败');
        }
    }

    /**
      * 栏目排序
      * @access private
      */
    private function _listOrder()
    {
      $orders=$_POST['sort'];
      foreach($orders as $k=>$v)
      {
        $map['id']=$k;
        $this->currentModel->where($map)->setField('sort_order',$v);
      }
      $this->currentModel->makeCacheFile($this->currentModel->getAllCategory(),MODULE_NAME);
      $this->success('操作成功',U(MODULE_NAME.'/index'));      
    }

    /**
      * 检查编辑栏目时上级栏目与本级栏目的冲突问题
      * 所选择的上级栏目不能是当前栏目或者当前栏目的子栏目
      * @access private
      * @param int $parentId
      * @param int $currentId
      */
    private function _parentCorrect($parentId,$currentId)
    {
      $this->tree->init($this->allCategory);
      $child=$this->tree->getChildString($currentId).$currentId;
      if(in_array($parentId,explode(',',$child)))
      {
          $this->error("所选择的上级栏目不能是当前栏目或者当前栏目的下级栏目!");
      }
    }
}
?>